{# SPDX-FileCopyrightText: © 2014 Siemens AG
   Author: J.Najjar

   SPDX-License-Identifier: GPL-2.0-only
#}

function initializeOption(myvalue) {
  var radios = $("input[name=FileSelection]:radio");
  radios.filter('[value=' + myvalue + ']').attr('checked', true);


  var uploadId = $('#upload').val();
  var uploadTreeId = $('#lastItem').val();

  setNextPrev(uploadId, uploadTreeId);
}

function setOptionOnChange(name) {
  $('#next').prop('disabled', true);
  $('#prev').prop('disabled', true);
  
  setOption(name, $('input[name=FileSelection]:radio:checked').val());

  var uploadId = $('#upload').val();
  var uploadTreeId = $('#lastItem').val();

  setNextPrev(uploadId, uploadTreeId);

}

function setNextPrev(uploadId, uploadTreeId) {
  $.getJSON("?mod=conclude-license&do={{ ajaxAction }}&upload=" + uploadId + "&item=" + uploadTreeId)
          .done(function (data) {
            var form = $('#{{ formName }}');
            var next = $('#next');
            if (data.next !== null) {
              next.prop('disabled', false);
              next.click(function () {
                form.attr('action', data.uri + '&item=' + data.next);
              });
            }
            else {
              next.prop('disabled', true);
            }
            var prev = $('#prev');
            if (data.prev !== null) {
              prev.prop('disabled', false);
              prev.click(function () {
                form.attr('action', data.uri + '&item=' + data.prev);
              });
            }
            else {
              prev.prop('disabled', true);
            }
          })
          .fail(failed);
}

$(document).ready(function () {
  var theOption = getOption("{{ optionName }}");
  if (theOption === "")
    theOption = "none";
  initializeOption(theOption);
  $('input[name=FileSelection]:radio').bind('change', function () {
    setOptionOnChange("{{ optionName }}");
  });
});
